﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cms.Core.Data.UnitOfWork;
using Cms.Core.IdentityServer4.Model;
using Cms.Core.Infrastructure.Dependency;
using Cms.Core.Infrastructure.Extensions;
using IdentityServer4.Quickstart.UI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Cms.Core.IdentityServer4
{
    public class Startup
    {
        public IHostingEnvironment Environment { get; }
        public Startup(IConfiguration configuration,IHostingEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public IConfiguration Configuration { get; }


        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;
            }); //测试用户

            builder.AddInMemoryIdentityResources(Config.GetIdentityResources());

            builder.AddInMemoryApiResources(Config.GetApiResources());

            builder.AddInMemoryClients(Config.GetClients());
            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }



            #region 注入上下文，注入工作单元，注入仓储
            services.AddDbContext<UnitOfWorkDbContext>(Configuration.GetConnectionString("DefaultConnection"));

            services.AddUnitOfWork<UnitOfWorkDbContext>();
            services.AddRepository();
            services.AddSingleton<IScopedServiceResolver, RequestScopedServiceResolver>(); //应该用动态注入
            //系统所有需要自动注入的DI
            services.AddCustomServices();
            #endregion

        }


        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }
}
